//
//  PayActivityInforViewController.m
//  AndCampus
//
//  Created by 史宵宵 on 2018/1/31.
//  Copyright © 2018年 史宵宵. All rights reserved.
//

#import "PayActivityInforViewController.h"
#import "WXApi.h"
#import <AlipaySDK/AlipaySDK.h>

@interface PayActivityInforViewController ()<UIGestureRecognizerDelegate>
@property (nonatomic,assign) BOOL isSending;

@end

@implementation PayActivityInforViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.moneyLabel.text = [NSString stringWithFormat:@"合计  ¥%@",self.moneyStr];
    self.isSending = NO;
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(alipayPaySuccess) name:@"AlipayPaySuccess" object:nil]; //授权微信成功发送通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(weiXinPaySuccess) name:@"WeiXinPaySuccess" object:nil]; //授权微信成功发送通知

    UITapGestureRecognizer *tap=[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(disSeleteMood:)];
    tap.delegate=self;
    [self.view addGestureRecognizer:tap];
    self.view.userInteractionEnabled = YES;
}
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
    if (touch.view==self.view) {
        return YES;
    }
    else
        return NO;
}
- (void)disSeleteMood:(UITapGestureRecognizer *)tap{
    [self.view endEditing:YES];
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}
- (IBAction)aliPay:(id)sender {
    UIButton *aliButton = (UIButton *)sender;
    aliButton.selected = !aliButton.isSelected;
    self.weChatButton.selected = aliButton.selected ? NO:self.weChatButton.selected;
}

- (IBAction)wechatPay:(id)sender {
    UIButton *weChatButton = (UIButton *)sender;
    weChatButton.selected = !weChatButton.isSelected;
    self.aliButton.selected = weChatButton.selected ? NO:self.weChatButton.selected;
}

- (IBAction)disViewController:(id)sender {
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}
#pragma mark - 支付
- (IBAction)nextStep:(id)sender {
    if (self.isSending) {
        return;
    }
    self.isSending = YES;
    YJNetWorkManger *yjNetWorkManger =  [YJNetWorkManger shareManager];
    NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
    [dic setValue:([self.payType isEqualToString:@"course"] || [self.payType isEqualToString:@"test"])? self.numId:self.activityInfo.fileEntryId forKey:@"no"]; //订单号
    [dic setValue:[Global getUserTokenInfo] forKey:@"token"]; //用户认证
    [dic setValue:[self.payType isEqualToString:@"course"]?@"2":[self.payType isEqualToString:@"test"]?@"3":@"1" forKey:@"bizType"]; //业务类型 (活动招募支付 1 课程传2)
    [dic setValue:([self.payType isEqualToString:@"course"] || [self.payType isEqualToString:@"test"])?self.moneyStr:self.activityInfo.fee forKey:@"amount"]; //金额单位（元）
    [dic setValue:self.weChatButton.selected?@"0":@"1" forKey:@"payType"]; //支付类型 0微信 1支付宝
    [dic setValue:([self.payType isEqualToString:@"course"] || [self.payType isEqualToString:@"test"])?self.titleStr:self.activityInfo.title forKey:@"subject"]; //title
    if (![self.payType isEqualToString:@"course"]) {
        [dic setValue:self.num forKey:@"num"]; //数量
        [dic setValue:self.orderId forKey:@"orderId"]; //订单号码
    }

    [yjNetWorkManger requestType:POST andURL:[JSPathUtil urlAppPayPrePay] andParmas:dic andComplition:^(id response, BOOL isuccess) {
        if (isuccess) {
            if (self.weChatButton.selected) {
                [self weixinPay:response];
            }else{
                [self Pay:response];
            }
            
        }
        self.isSending = NO;
    }];
}
#pragma mark - 支付宝支付
- (void)Pay:(NSDictionary*)dic{
    // NOTE: 将签名成功字符串格式化为订单字符串,请严格按照该格式
//    NSString *orderString = [NSString stringWithFormat:@"%@&sign=%@",
//                             dic[@"orderInfoEncoded"], dic[@"signedString"]];
//    NSString *appScheme = @"alisdkdemo";
    // NOTE: 调用支付结果开始支付
    [[AlipaySDK defaultService] payOrder:dic[@"content"] fromScheme:ALiPAYAppid callback:^(NSDictionary *resultDic) {
        NSLog(@"reslut = %@",resultDic);
    }];
}
#pragma mark - 微信支付
- (void)weixinPay:(NSDictionary*)dic{
    PayReq *request = [[PayReq alloc] init];
    request.partnerId = dic[@"partnerid"];
    request.prepayId= dic[@"prepayid"];
    request.package = dic[@"packageStr"];
    request.nonceStr= dic[@"nonceStr"];
    request.timeStamp= [dic[@"timeStamp"] intValue];
    request.sign= dic[@"paySign"];
    [WXApi sendReq:request];
}
#pragma mark -支付宝支付成功
- (void)alipayPaySuccess{
    MyLog(@"支付宝支付成功");
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
    if (self.paySuccessBlack) {
        self.paySuccessBlack();
    }
}
#pragma mark -微信支付成功
- (void)weiXinPaySuccess{
    MyLog(@"微信支付成功");
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
    if (self.paySuccessBlack) {
        self.paySuccessBlack();
    }
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
/*
 {
 timeStamp = <null>,
 returnUrl = "http://47.104.6.78/pay/returnAli/httpAction?orderid=18020217565300000022&userid=109&channel=0",
 partnerid = <null>,
 amount = 0,
 nonceStr = <null>,
 paySign = <null>,
 merchantId = <null>,
 sellerid = "ziyushi666@163.com",
 appId = <null>,
 code = 0,
 err = <null>,
 orderid = "18020217565300000022",
 packageStr = <null>,
 signType = <null>,
 notifyurl = "http://47.104.6.78/pay/notifyAli/httpAction",
 pid = "2088921298312274",
 msg = <null>,
 prepayid = <null>,
 content = "alipay_sdk=alipay-sdk-java-dynamicVersionNo&app_id=2018011401854871&biz_content=%7B%22body%22%3A%22%E7%B2%BE%E7%BE%8E%22%2C%22out_trade_no%22%3A%2218020217565300000022%22%2C%22product_code%22%3A%22QUICK_MSECURITY_PAY%22%2C%22subject%22%3A%22%E7%B2%BE%E7%BE%8E%22%2C%22timeout_express%22%3A%2230m%22%2C%22total_amount%22%3A%220.01%22%7D&charset=utf-8&format=json&method=alipay.trade.app.pay&notify_url=http%3A%2F%2F47.104.6.78%2Fpay%2FnotifyAli%2FhttpAction&sign=TiQHdDFJ4tVux3CdExhIL9BXRaUuTwpXz40ZrCiGTJWCEawE3508lENNeLKX63HKIwYSlYEaZF5J6EXpRFLbGGjx6w%2FQWT2z6Zwz3%2BGUJnV8BwNmvkwImeuuhPCNjvk4M0Y3tGZAxgYUJlivVPVvgNzyhTJ6tvBTk1TWm19TO9WQgfXiSipU%2BEVAPtkbsrYb91VZann6tqd2RR9sVQkyup38tcQnukDDHyUjCfszHMCiroODlilPWKO4ZO9cE%2BRsAOBuVTYD78S3B6I73uXV0FY%2FDGVerXxe4bR6HK%2FDen1EMrc5uxLwy6Tjfq1CfGiKhX36bxgiGjWWMvdrlXSUaw%3D%3D&sign_type=RSA2&timestamp=2018-02-02+17%3A57%3A08&version=1.0",
 },
 */
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
